package com.battlebardgames.simplejavacache.example;

import java.io.Serializable;
import java.util.Random;

import com.battlebardgames.simplejavacache.CacheEngine;
import com.battlebardgames.simplejavacache.cache.QueryBasedCache;
import com.battlebardgames.simplejavacache.cache.RuntimeCache;
import com.battlebardgames.simplejavacache.cache.database.ConnectionPoolFactory;
import com.battlebardgames.simplejavacache.cache.database.MySqlDatabaseCache;
import com.battlebardgames.simplejavacache.key.MD5KeyProvider;
import com.battlebardgames.simplejavacache.key.PerInstanceKeyProvider;
import com.jolbox.bonecp.BoneCP;

/**
 * A caching example
 * @author Thomas Cashman
 */
public class CacheExample implements ICacheExample, Serializable {
	private static final long serialVersionUID = 1L;

	public static void main(String [] args) {
		/* Create database cache instance */
		BoneCP connectionPool = ConnectionPoolFactory.createConnectionPool(
				"com.mysql.jdbc.Driver", 
				"jdbc:mysql://localhost:8889/sjc_cache_example", 
				"root", "root");
		MySqlDatabaseCache dbCache = new MySqlDatabaseCache(connectionPool);
		
		/* Build cache */
		CacheEngine.initialise(new QueryBasedCache(
				dbCache, new RuntimeCache(), 3), 
				new MD5KeyProvider(new PerInstanceKeyProvider()));
		String objectKey1 = CacheEngine.cache(new CacheExample());
		
		/* Fetch cached instance */
		ICacheExample objectInstance = (ICacheExample)
				CacheEngine.getObject(objectKey1);
		
		/* Call method initially and then 
		 * call again to show cached result */
		System.out.println("DB cache result: " + objectInstance.getRandom());
		System.out.println("DB cache result: " + objectInstance.getRandom());
		System.out.println("DB cache result: " + objectInstance.getRandom());
		System.out.println("Runtime cache result: " + objectInstance.getRandom());
		
		/* Close the connection pool */
		connectionPool.close();
	}

	@Override
	public int getRandom() {
		Random random = new Random();
		int result = random.nextInt();
		System.out.println("Implementation result: " + result);
		return result;
	}
}
